package com.lhd._05mvcboot03.common.exception;

import com.lhd._05mvcboot03.common.response.JsonResult;
import com.lhd._05mvcboot03.common.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

/**
 * @author lhd
 * @date 2024/4/26
 * @apiNote
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler
    //不合法参数
    public JsonResult doHandleIllegalArgumentException(IllegalArgumentException ex) {
        log.error("message = ", ex);
        return new JsonResult(StatusCode.OPERATION_FAILED,ex);
    }

    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        log.error("message = " + ex.getMessage());

        return new JsonResult(StatusCode.VALIDATED_ERROR,ex.getFieldError().getDefaultMessage());
    }

    @ExceptionHandler
    public JsonResult doHandle(ConstraintViolationException ex){
        log.error("message = " + ex.getMessage());
        String message = ex.getMessage().split(":")[1].trim();

        return new JsonResult(StatusCode.VALIDATED_ERROR, message);
    }
}
